App = {
    web3Provider: null,
    contracts: {},
  
    init: async function() {
      // Load pets.
      console.log("initial over")
      return await App.initWeb3();
    },
  
    initWeb3: function() {
  
      // Modern dapp browsers...
      if (window.ethereum) {
        App.web3Provider = window.ethereum;
        try {
          // Request account access
          window.ethereum.enable();
        } catch (error) {
          // User denied account access...
          console.error("User denied account access")
        }
      }
      // Legacy dapp browsers...
      else if (window.web3) {
        App.web3Provider = window.web3.currentProvider;
      }
      // If no injected web3 instance is detected, fall back to Ganache
      else {
        App.web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');
      }
      web3 = new Web3(App.web3Provider);
  
      return App.initContract();
    },
  
    initContract: function() {
      // 加载Adoption.json，保存了Adoption的ABI（接口说明）信息及部署后的网络(地址)信息，它在编译合约的时候生成ABI，在部署的时候追加网络信息
      $.getJSON('Provance.json', function(data) {
        // 用Adoption.json数据创建一个可交互的TruffleContract合约实例。
        var ProvanceArtifact = data;
        App.contracts.Provance = TruffleContract(ProvanceArtifact);
    
        // Set the provider for our contract
        App.contracts.Provance.setProvider(App.web3Provider);
        console.log("initcontract")
    
        // Use our contract to retrieve and mark the adopted pets
        //这一步应该替换称什么；（****************8）
        return App.provanceDate();
      });
      return App.bindEvents();
    },
  
    bindEvents: function() {
        document.getElementById("queryall").onclick=App.handleAllQuery
    },

    provanceDate:function(){
        var provanceInstance;
        App.contracts.Provance.deployed().then(function(instance) {
            provanceInstance = instance;
            console.log("init")
            //调用合约的setMeterialInfo, 用call读取信息不用消耗gas
            provanceInstance.setProduceInfo("00002","科尔达","生产1号","normal");
            provanceInstance.setTradesInfo("00002","思科","经销1号","normal");
            provanceInstance.setRetailsInfo("00002","系达瓦","零售1号","normal");
            return provanceInstance.setMeterialInfo("00002","泰通","富士康","2020-3-18","none","50");

          }).catch(function(err) {
            console.log(err.message);
          });
    },

    handleAllQuery:function(){
        var IDNeed=document.getElementById("IDCard").value;

        var provanceInstance;
  
        // App.contracts.Provance.deployed().then(function(instance) {
        //     provanceInstance = instance;
  
        //   // 发送交易领养宠物
        //   return provanceInstance.getMeterialInfo(IDNeed);
        // }).then(function(result) {
        //     console.log(result)
        //     document.getElementById("Meterial").innerHTML=result
        // }).catch(function(err) {
        //   console.log(err.message);
        // });

        App.contracts.Provance.deployed().then(function(instance) {
            provanceInstance = instance;
            return provanceInstance;
        }).then(function(proinstance) {
            return proinstance.getMeterialInfo(IDNeed); 
        }).then(function(result){
            document.getElementById("Meterial").innerHTML=result
        }).catch(function(err) {
          console.log(err.message);
        });

        App.contracts.Provance.deployed().then(function(instance) {
            provanceInstance = instance;
            return provanceInstance;
        }).then(function(proinstance) {
            return proinstance.getProduceInfo(IDNeed); 
        }).then(function(result){
            document.getElementById("Produce").innerHTML=result
        }).catch(function(err) {
          console.log(err.message);
        });

        App.contracts.Provance.deployed().then(function(instance) {
            provanceInstance = instance;
            return provanceInstance;
        }).then(function(proinstance) {
            return proinstance.getTradesInfo(IDNeed); 
        }).then(function(result){
            document.getElementById("Trades").innerHTML=result
        }).catch(function(err) {
          console.log(err.message);
        });

        App.contracts.Provance.deployed().then(function(instance) {
            provanceInstance = instance;
            return provanceInstance;
        }).then(function(proinstance) {
            return proinstance.getRetailsInfo(IDNeed); 
        }).then(function(result){
            document.getElementById("Retails").innerHTML=result
        }).catch(function(err) {
          console.log(err.message);
        });


        
    },
    markAdopted: function(adopters, account) {
      var adoptionInstance;
  
      App.contracts.Adoption.deployed().then(function(instance) {
        adoptionInstance = instance;
        console.log("initmark")
        // 调用合约的getAdopters(), 用call读取信息不用消耗gas
        return adoptionInstance.getAdopters.call();
      }).then(function(adopters) {
        console.log(adopters)
        for (i = 0; i < adopters.length; i++) {
          if (adopters[i] !== '0x0000000000000000000000000000000000000000') {
            $('.panel-pet').eq(i).find('button').text('Success').attr('disabled', true);
          }
        }
      }).catch(function(err) {
        console.log(err.message);
      });
    },
    handleAdopt: function(event) {
      event.preventDefault();
  
      var petId = parseInt($(event.target).data('id'));
      console.log(petId)
      var adoptionInstance;
  
      // 获取用户账号
      web3.eth.getAccounts(function(error, accounts) {
        if (error) {
          console.log(error);
        }
        console.log(accounts)
        var account = accounts[0];
        console.log(account)
  
        App.contracts.Adoption.deployed().then(function(instance) {
          adoptionInstance = instance;
  
          // 发送交易领养宠物
          return adoptionInstance.adopt(petId, {from: account});
        }).then(function(result) {
          return App.markAdopted();
        }).catch(function(err) {
          console.log(err.message);
        });
      });
    }
    
  
  };
  
  $(function() {
    $(window).load(function() {
      App.init();
    });
  });
  